/**
 * pagination - jQuery xui
 *
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2013 xjb [ beymy.en@gmail.com ]
 *
 * 依赖
 *   linkbutton
 */
(function($) {
    /**
     * 构建分页工具栏
     */
    function buildPagination(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target).addClass('pagination').empty();

        var pagination = ['<table cellspacing="0" cellpadding="0" border="0"><tr>']; //用table解决居中对齐问题
        if (opts.showPageList) {
            pagination.push('<td><select class="pagination-page-list">');
            for (var i = 0; i < opts.pageList.length; i++) {
            	if(opts.pageSize == opts.pageList[i]) {
                	pagination.push('<option selected>' + opts.pageList[i] + '</option>');
            	} else {
            		pagination.push('<option>' + opts.pageList[i] + '</option>');
            	}
            }
            pagination.push('</select></td>');
            pagination.push('<td><div class="pagination-btn-separator"></div></td>');
        }
        pagination.push('<td><a href="javascript:void(0)" iconCls="pagination-first"></a></td>');
        pagination.push('<td><a href="javascript:void(0)" iconCls="pagination-prev"></a></td>');
        pagination.push('<td><div class="pagination-btn-separator"></div></td>');
        pagination.push('<td><span class="pagination-before-page">第</span></td><td><input type="text" class="pagination-num"/></td><td><span class="pagination-after-page">共{pages}页</span></td>');
        pagination.push('<td><div class="pagination-btn-separator"></div></td>');
        pagination.push('<td><a href="javascript:void(0)" iconCls="pagination-next"></a></td>');
        pagination.push('<td><a href="javascript:void(0)" iconCls="pagination-last"></a></td>');
        if (opts.showRefresh) {
            pagination.push('<td><div class="pagination-btn-separator"></div></td>');
            pagination.push('<td><a href="javascript:void(0)" iconCls="pagination-reload"></a></td>');
        }
        pagination.push('</tr></table>');
        pagination.push('<span class="pagination-info">共{total}条记录</span>');
        pagination.push('<div style="clear:both;"></div>');

        pager.html(pagination.join(''));

        $('a[iconCls^="pagination"]', pager).linkbutton({
            plain: true
        });
    }

    /**
     * 绑定事件
     */
    function bindEvents(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target);

        $('a[iconCls="pagination-first"]', pager).unbind('.pagination').bind('click.pagination', function() {
            if (opts.pageNumber > 1) {
                selectPage(target, 1);
            }
        });
        $('a[iconCls="pagination-prev"]', pager).unbind('.pagination').bind('click.pagination', function() {
            if (opts.pageNumber > 1) {
                selectPage(target, opts.pageNumber - 1);
            }
        });
        $('a[iconCls="pagination-next"]', pager).unbind('.pagination').bind('click.pagination', function() {
            var pageCount = Math.ceil(opts.total / opts.pageSize);
            if (opts.pageNumber < pageCount) {
                selectPage(target, opts.pageNumber + 1);
            }
        });
        $('a[iconCls="pagination-last"]', pager).unbind('.pagination').bind('click.pagination', function() {
            var pageCount = Math.ceil(opts.total / opts.pageSize);
            if (opts.pageNumber < pageCount) {
                selectPage(target, pageCount);
            }
        });
        $('a[iconCls="pagination-reload"]', pager).unbind('.pagination').bind('click.pagination', function() {
            selectPage(target, opts.pageNumber);
        });
        $('input.pagination-num', pager).unbind('.pagination').bind('keydown.pagination', function(e) {
            if (e.keyCode == 13) {
                var pageNumber = parseInt($(this).val()) || 1;
                selectPage(target, pageNumber);
            }
        });
        $('select.pagination-page-list', pager).unbind('.pagination').bind('change.pagination', function() {
            opts.pageSize = $(this).val();
            selectPage(target, opts.pageNumber);
        });
    }

    function selectPage(target, pageNumber) {
        var opts = $.data(target, 'pagination').options;
        var pageCount = Math.ceil(opts.total / opts.pageSize);
        if (pageNumber > pageCount) pageNumber = pageCount;
        if (pageNumber < 1) pageNumber = 1; //页码最小是1
        opts.onSelectPage.call(target, pageNumber, opts.pageSize);
        opts.pageNumber = pageNumber;
        showPagerInfo(target);
    }

    function showPagerInfo(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target);
        var pageCount = Math.ceil(opts.total / opts.pageSize);

        if (pageCount < 1) { //总页码数最小是1
            pageCount = 1;
        }

        $('input.pagination-num', pager).val(opts.pageNumber);
        $('span.pagination-after-page', pager).html(opts.afterPageText.replace(/{pages}/, pageCount));

        $('span.pagination-info', pager).html(opts.displayMsg.replace(/{total}/, opts.total));
        $('a[iconCls="pagination-first"],a[iconCls="pagination-prev"]', pager).linkbutton('disable', (opts.pageNumber == 1));
        $('a[iconCls="pagination-next"],a[iconCls="pagination-last"]', pager).linkbutton('disable', (opts.pageNumber == pageCount));
        setLoadStatus(target, opts.loading);
    }

    function setLoadStatus(target, loading) {
        var opts = $.data(target, 'pagination').options;
        opts.loading = loading;
        if (opts.loading) {
            $(target).find('a[iconCls="pagination-reload"]').find('.pagination-reload').addClass('pagination-loading');
        } else {
            $(target).find('a[iconCls="pagination-reload"]').find('.pagination-reload').removeClass('pagination-loading');
        }
    }

    $.fn.pagination = function(options, param) {
        if (typeof options == 'string') {
            return $.fn.pagination.methods[options](this, param);
        }

        options = options || {};
        return this.each(function() {
            var opts;
            var state = $.data(this, 'pagination');
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.pagination.defaults, options);
                $.data(this, 'pagination', {
                    options: opts
                });
                buildPagination(this); //不支持动态界面变化
                bindEvents(this);
            }
            showPagerInfo(this);
        });
    };

    $.fn.pagination.methods = {
        options: function(jq) {
            return $.data(jq[0], "pagination").options;
        },
        loading: function(jq) {
            return jq.each(function() {
                setLoadStatus(this, true);
            });
        },
        loaded: function(jq) {
            return jq.each(function() {
                setLoadStatus(this, false);
            });
        },
        select: function(jq, param) {
            return jq.each(function() {
                selectPage(this, param);
            });
        }
    };

    $.fn.pagination.parseOptions = function(target) {
        return $.extend({}, $.parser.parseOptions(target, [{
            total: 'number',
            pageSize: 'number',
            pageNumber: 'number',
            pageList: 'array'
        }, {
            loading: 'boolean',
            showPageList: 'boolean',
            showRefresh: 'boolean'
        }]));
    };

    $.fn.pagination.defaults = {
        total: 0,
        pageSize: 10,
        pageNumber: 1,
        pageList: [10, 20, 30, 50],
        loading: false,
        buttons: null,
        showPageList: true,
        showRefresh: true,

        onSelectPage: function(pageNumber, pageSize) {},
        onBeforeRefresh: function(pageNumber, pageSize) {},
        onRefresh: function(pageNumber, pageSize) {},
        onChangePageSize: function(pageSize) {},

        beforePageText: '第',
        afterPageText: '共{pages}页',
        displayMsg: '共{total}条记录'
    };
})(jQuery);
